<?php
namespace App\Repos;

use App\Models\UserGroupbuy;
use App\Models\ProductGroup;
use App\Models\Order;
use DB;
use Carbon\Carbon;

class UserGroupbuyRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$list = UserGroupbuy::select(['shop_id','product_id','product_num','end_at'])->with('product:id,name,thumb,price')->where($where)->paginate($num); 
	  	return $list;     
	}

	public static function create($data)
	{
		$rs['status'] = false;

		// 商品是否可以团
		$map['id']      = $data['product_id'];
		$map['type_id'] = 2;
		$pro = ProductRepo::find($map);
		if(!$pro) {
			$rs['msg'] = '商品类型错误';
			return $rs;
		}

		// 如果已经发起此产品的拼团那么直接返回拼团信息
		$where = array_only($data, ['user_id', 'product_group_id']);
		$where['parent_id'] = 0;	
		$where['status']    = 1;
		if(array_get($data,'parent_id',0)==0) {
			
			$flag  = UserGroupbuy::where($where)->first();
			if($flag) {
				$rs['msg'] = '您已经发起过本商品的拼团';
				return $rs;
			}
		} else {
			// 跟团查看自己有没有发起过同款，可以跟自己的，如果跟别人的要提示
			//$where['parent_id'] = $data['parent_id'];	
			$parent = UserGroupbuy::find($data['parent_id']);

			$had = UserGroupbuy::where($where)->first();
			
			
			// 是否保留原来的团，第二次才传
			$had_ok = array_pull($data,'had_ok');
			//dd($had,$parent,$where,$had_ok);
			// 不是跟自己的团
			if(empty($had_ok) && $had &&  $parent->user_id!=$data['user_id']) {
					$rs['msg'] = '您之前已经生成过此商品的拼团订单，是否保留原来的拼团？';
					$rs['data']['group_code']    = $had->code;	
					$rs['had_group'] = true;
					return $rs;				
					
			}
		}


		
		

		//团购信息
		$productGroup = ProductGroup::find($data['product_group_id']);
		try {
			DB::beginTransaction();
			if(array_get($data,'parent_id')) {		
				

				$ugb = UserGroupbuy::find($data['parent_id']);

				

				if($ugb->status!=1) {
					$rs['msg'] = '拼团活动已经结束,无法跟团';
					return $rs;
				}
				$data['code']   = $ugb->code;
				$data['end_at'] = $ugb->end_at;
			} else {
				$data['code']   = str_random(16);
				$data['end_at'] = Carbon::now()->addHours($productGroup->valid_time);
			}
			
			$flag = UserGroupbuy::create($data);
			DB::commit();			
		} catch (\Exception $e) {
			
			$rs['msg']    = $e->getMessage();
			DB::rollBack();
			return $rs;
		}
		// 如果是跟单就用父id的code，新发起的就生成code
		$rs['status'] = true;		
		return $rs;		
	}

	// 参与拼单
	public static function follow($data)
	{

	}

	public static function find($where=[])
	{
		return UserGroupbuy::where($where)
							->orderBy('created_at','desc')
							->first();
	}

	public static function cancle($where)
	{
		return UserGroupbuy::where($where)->update(['status'=>'-2']);
	}

	public static function update($where=[],$data)
	{
		return UserGroupbuy::where($where)->update($data);
	}

	public static function countNum($code)
	{
		$where['code']   = $code;
		$where['status'] = 1;
		return UserGroupbuy::where($where)->count();
	}


	
	
	

	
	
	
}